package com.itheima.controller;

import com.itheima.domain.Book;
import com.itheima.exception.BusinessException;
import com.itheima.exception.SystemException;
import com.itheima.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping
    public Result findAll(){
        List<Book> list = bookService.findAll();
        Result result = new Result(Code.SELETE_OK, list, "查询成功");
        return result;
    }

    @GetMapping("/{id}")
    public Result findByid(@PathVariable Integer id){
        if (id ==1 ){
           throw new BusinessException(Code.BUSIN_ERR,"你这输入有问题啊");
        }else if (id == 2 ){
            throw new SystemException(Code.SYSTY_ERR,"系统问题，正在打电话喊员工");
        }else if (id == 3 ){
            int i = id / 0;
        }

        Book book = bookService.findByid(id);
        Result result = new Result(Code.SELETE_OK, book, "查询成功");
        return result;
    }

    @PostMapping
    public Result save(@RequestBody Book book){
        Boolean flag = bookService.save(book);
        Result result = new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR , null , flag ? "添加成功" : "添加失败");
        return result;
    }

    @PutMapping
    public Result update(@RequestBody Book book){
        Boolean flag = bookService.update(book);
        Result result = new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR , null , flag ? "修改成功" : "修改失败");
        return result;
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        Boolean flag = bookService.delete(id);
        Result result = new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR , null , flag ? "删除成功" : "删除失败");
        return result;
    }
}
